<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AppException;
use App\Models\Data;
use App\Models\Member;
use App\Services\ExcelExportService;
use Illuminate\Http\Request;

class DataController extends BaseController {

    /**
     * 首页数据
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $params = $request->all();
        $build = Data::query();
        $pageSize = $request->input('pageSize', 50);
        if (isset($params['start_time']) && isset($params['end_time'])){
            $build = $build->whereBetween('created_at', [$params['start_time'], $params['end_time']]);
        }

        if (isset($params['mr'])){
            $build = $build->where('name', $params['mr']);
        }
        $data = $build->paginate($pageSize);
        return $this->success($data);
    }

    /**
     * 导出excel
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws AppException
     */
    public function export(Request $request)
    {
        $params = $request->all();

        try {
            $directory = storage_path('excel') . '/export';
            $fileName = rand(1000, 9999) . time() . ".xlsx";//导出文件名
            $header = [
                'name' => '姓名', 'province_info' => '城市', 'team_info' => '团队', 'rm_info' => 'RM', 'dm_info' => 'DM',
                'dme_big' => 'dme_big', 'dme_new' => 'dme_new', 'dme_old' => 'dme_old', 'wamd_big' => 'wamd_big', 'wamd_new' => 'wamd_new',
                'wamd_old' => 'wamd_old', 'pcv_big' => 'pcv_big', 'pcv_new' => 'pcv_new', 'pcv_old' => 'pcv_old', 'other_big' => 'other_big',
                'other_new' => 'other_new', 'other_old' => 'other_old', 'created_at' => '创建日期'
            ];
            $widthArray = ['A' => 10, 'B' => 10, 'C' => 10, 'D' => 10, 'E' => 10];
            $build = Data::query();
            if (isset($params['start_time']) && isset($params['end_time'])){
                $build = $build->whereBetween('created_at', [$params['start_time'], $params['end_time']]);
            }

            if (isset($params['mr'])){
                $build = $build->where('name', $params['mr']);
            }
            $service = new ExcelExportService();
            $service->exportDataBySheet($directory, $fileName, $build, $header, '', 2000, $widthArray);
            return response()->download($directory . '/' . $fileName, '导出文件.xlsx', $headers = ['Content-Type' => 'application/zip;charset=utf-8']);
        } catch (\ Exception $exception) {
            echo $exception->getMessage();die;
            throw new AppException('export_fail');
        }
    }

    /**
     * 获取下拉菜单选项数据
     * @param Request $request
     * @return array
     */
    public function select(Request  $request)
    {
        try {
            $params = $request->all();
            $build = Member::query();
            if (isset($params['team'])){
                $team = $params['team'];
                $build->where('team_info', 'like', "%$team%");
            }
            if (isset($params['rm'])){
                $rm = $params['rm'];
                $build->where('rm_info', 'like', "%$rm%");
            }
            if (isset($params['dm'])){
                $dm = $params['dm'];
                $build->where('dm_info', 'like', "%$dm%");
            }
            if (isset($params['province'])){
                $province = $params['province'];
                $build->where('province_info', 'like', "%$province%");
            }
            if (isset($params['mr'])){
                $mr = $params['mr'];
                $build->where('name', 'like', "%$mr%");
            }

            $data = $build->get()->toArray();

            //处理rm
            $rm = array_column($data,'rm_info');
            $rmStr = '';
            foreach ($rm as $key => $value){
                $rmStr = $rmStr .',' . $value;
            }
            $rmStr = trim($rmStr, ',');
            $rmStr = str_replace("，",",",$rmStr);
            $rm = array_unique(explode(',', $rmStr));

            //处理dm
            $dm = array_column($data,'dm_info');
            $dmStr = '';
            foreach ($dm as $key => $value){
                $dmStr = $dmStr .',' . $value;
            }
            $dmStr = trim($dmStr, ',');
            $dmStr = str_replace("，",",",$dmStr);
            $dm = array_unique(explode(',', $dmStr));

            //处理province_info
            $province = array_column($data,'province_info');
            $provinceStr = '';
            foreach ($province as $key => $value){
                $provinceStr = $provinceStr .',' . $value;
            }
            $provinceStr = trim($provinceStr, ',');
            $provinceStr = str_replace("，",",",$provinceStr);
            $province = array_unique(explode(',', $provinceStr));

            //处理mr
            $mr = array_column($data,'name');
            $dmList = [];
            $rmList = [];
            $mrList = [];
            $provinceList = [];
            foreach ($dm as $key => $value){
                if ($value != ''){
                    $dmList[$value] = $value;
                }
            }
            foreach ($rm as $key => $value){
                if ($value != ''){
                    $rmList[$value] = $value;
                }
            }
            foreach ($mr as $key => $value){
                $mrList[$value] = $value;
            }
            foreach ($province as $key => $value){
                if ($value != ''){
                    $provinceList[$value] = $value;
                }
            }

            $result = [
                'dm_list' => $dmList,
                'rm_list' => $rmList,
                'mr_list' => $mrList,
                'province_list' => $provinceList,
            ];
            return $this->success($result);

        } catch (\Exception $exception){
            return $this->error([$exception]);
        }
    }

    /**
     * 获取数据详情
     * @param Request $request
     * @return array
     */
    public function statistics(Request $request)
    {
        $params = $request->all();
        $build = Data::query();
        $allDayBuild = Data::query();


        if (isset($params['team'])){
            $team = $params['team'];
            $build->where('team_info', 'like', "%$team%");
        }
        if (isset($params['rm'])){
            $rm = $params['rm'];
            $build->where('rm_info', 'like', "%$rm%");
        }
        if (isset($params['dm'])){
            $dm = $params['dm'];
            $build->where('dm_info', 'like', "%$dm%");
        }
        if (isset($params['province'])){
            $province = $params['province'];
            $build->where('province_info', 'like', "%$province%");
        }
        if (isset($params['mr'])){
            $mr = $params['mr'];
            $build->where('name', 'like', "%$mr%");
            $allDayBuild->where('name', $params['mr']);
        }

        if (isset($params['start_time']) && isset($params['end_time'])){
            $build->whereBetween('created_at', [$params['start_time'], $params['end_time']]);
        }
        $data = $build->get()->toArray();

        $today = date("Y-m-d");
        $day= $this->getTheMonth($today);

        $firstDay = strtotime($day[0]);
        $lastDay = strtotime($day[1]);

        $allDay = $allDayBuild->whereBetween('created_at', [$firstDay, $lastDay])->get()->toArray();
        $result = [];
        $result['dme_big'] = array_sum(array_column($data,'dme_big'));
        $result['dme_new'] = array_sum(array_column($data,'dme_new'));
        $result['dme_old'] = array_sum(array_column($data,'dme_old'));
        // $result['dme_preferred_rate'] =  $result['dme_new'] == 0 ? 0 : $this->formatDecimal(round($result['dme_new'] / ( $result['dme_big'] * 0.6 ), 4),2);
        if ($result['dme_new'] == 0 || $result['dme_big'] == 0) {
            $result['dme_preferred_rate'] = 0;
        }else{
            $result['dme_preferred_rate'] = $this->formatDecimal(round($result['dme_new'] / ( $result['dme_big'] * 0.6 ), 4),2);
        }
        $result['dme_preferred_rate_month'] = array_sum(array_column($allDay,'dme_big')) == 0 ? 0 :
            $this->formatDecimal(round(array_sum(array_column($allDay,'dme_new')) / ( array_sum(array_column($allDay,'dme_big')) * 0.6 ), 4),2);

        $result['other_big'] = array_sum(array_column($data,'other_big'));
        $result['other_new'] = array_sum(array_column($data,'other_new'));
        $result['other_old'] = array_sum(array_column($data,'other_old'));
        // $result['other_preferred_rate'] =  $result['other_new'] == 0 ? 0 : $this->formatDecimal(round($result['other_new'] / ( $result['other_big'] * 0.6 ), 4),2);
        if ($result['other_new'] == 0 || $result['other_big'] == 0) {
            $result['other_preferred_rate'] = 0;
        }else{
            $result['other_preferred_rate'] = $this->formatDecimal(round($result['other_new'] / ( $result['other_big'] * 0.6 ), 4),2);
        }
        $result['other_preferred_rate_month'] = array_sum(array_column($data,'other_old'));
        $result['other_preferred_rate_month'] = array_sum(array_column($allDay,'other_big')) == 0 ? 0 :
            $this->formatDecimal(round(array_sum(array_column($allDay,'other_new')) / ( array_sum(array_column($allDay,'other_big')) * 0.6 ), 4),2);

        $result['pcv_big'] = array_sum(array_column($data,'pcv_big'));
        $result['pcv_new'] = array_sum(array_column($data,'pcv_new'));
        $result['pcv_old'] = array_sum(array_column($data,'pcv_old'));
        // $result['pcv_preferred_rate'] =  $result['pcv_new'] == 0 ? 0 : $this->formatDecimal(round($result['pcv_new'] / ( $result['pcv_big'] * 0.6 ), 4),2);
        if ($result['pcv_new'] == 0 || $result['pcv_big'] == 0) {
            $result['pcv_preferred_rate'] = 0;
        }else{
            $result['pcv_preferred_rate'] = $this->formatDecimal(round($result['pcv_new'] / ( $result['pcv_big'] * 0.6 ), 4),2);
        }
        $result['pcv_preferred_rate_month'] = array_sum(array_column($data,'pcv_old'));
        $result['pcv_preferred_rate_month'] = array_sum(array_column($allDay,'pcv_big')) == 0 ? 0 :
            $this->formatDecimal(round(array_sum(array_column($allDay,'pcv_new')) / ( array_sum(array_column($allDay,'pcv_big')) * 0.6 ), 4),2);

        $result['wamd_big'] = array_sum(array_column($data,'wamd_big'));
        $result['wamd_new'] = array_sum(array_column($data,'wamd_new'));
        $result['wamd_old'] = array_sum(array_column($data,'wamd_old'));
        // $result['wamd_preferred_rate'] =  $result['wamd_new'] == 0 ? 0 : $this->formatDecimal(round($result['wamd_new'] / ( $result['wamd_big'] * 0.6 ), 4),2);

        if ($result['wamd_new'] == 0 || $result['wamd_big'] == 0) {
            $result['wamd_preferred_rate'] = 0;
        }else{
            $result['wamd_preferred_rate'] = $this->formatDecimal(round($result['wamd_new'] / ( $result['wamd_big'] * 0.6 ), 4),2);
        }
        $result['wamd_preferred_rate_month'] = array_sum(array_column($data,'wamd_old'));
        $result['wamd_preferred_rate_month'] = array_sum(array_column($allDay,'wamd_big')) == 0 ? 0 :
            $this->formatDecimal(round(array_sum(array_column($allDay,'wamd_new')) / ( array_sum(array_column($allDay,'wamd_big')) * 0.6 ), 4),2);

        $year = date("Y");
        //根据当前时间。计算  再治疗率
        $mouth = date("m");
        for ($x=1; $x <= 12; $x++) {
            //如果当前月还没结束则展示  -
            if ($x >= $mouth){
                $result['re_treatment_rate' . $x] = '--'; continue;
            }
            $getFirstAndLast= $this->getFirstAndLast($year,$x);

            $firstDay = $getFirstAndLast['firstDay'];
            $lastDay = $getFirstAndLast['lastDay'];

            $espDataBuild = Data::query()
                ->where('created_at', '>=', $firstDay)
                ->where('created_at', '<=', $lastDay);

            if (isset($params['team'])){
                $team = $params['team'];
                $espDataBuild->where('team_info', 'like', "%$team%");
            }
            if (isset($params['rm'])){
                $rm = $params['rm'];
                $espDataBuild->where('rm_info', 'like', "%$rm%");
            }
            if (isset($params['dm'])){
                $dm = $params['dm'];
                $espDataBuild->where('dm_info', 'like', "%$dm%");
            }
            if (isset($params['province'])){
                $province = $params['province'];
                $espDataBuild->where('province_info', 'like', "%$province%");
            }
            if (isset($params['mr'])){
                $mr = $params['mr'];
                $espDataBuild->where('name', 'like', "%$mr%");
            }

            $espData = $espDataBuild->get()->toArray();

            $dme_old = array_sum(array_column($espData,'dme_old'));
            $other_old = array_sum(array_column($espData,'other_old'));
            $pcv_old = array_sum(array_column($espData,'pcv_old'));
            $wamd_old = array_sum(array_column($espData,'wamd_old'));
            $esp = $dme_old + $other_old + $pcv_old + $wamd_old;

            //enp 需要取上个月的
            if ($x == 1){
                $getFirstAndLast= $this->getFirstAndLast($year-1,12);
            }else{
                $getFirstAndLast= $this->getFirstAndLast($year,$x-1);
            }
            $firstDay = $getFirstAndLast['firstDay'];
            $lastDay = $getFirstAndLast['lastDay'];

            $enpDataBuild = Data::query()
                ->where('created_at', '>=', $firstDay)
                ->where('created_at', '<=', $lastDay);

            if (isset($params['team'])){
                $team = $params['team'];
                $enpDataBuild->where('team_info', 'like', "%$team%");
            }
            if (isset($params['rm'])){
                $rm = $params['rm'];
                $enpDataBuild->where('rm_info', 'like', "%$rm%");
            }
            if (isset($params['dm'])){
                $dm = $params['dm'];
                $enpDataBuild->where('dm_info', 'like', "%$dm%");
            }
            if (isset($params['province'])){
                $province = $params['province'];
                $enpDataBuild->where('province_info', 'like', "%$province%");
            }
            if (isset($params['mr'])){
                $mr = $params['mr'];
                $enpDataBuild->where('name', 'like', "%$mr%");
            }
            $enpData = $enpDataBuild->get()->toArray();
            $dme_new = array_sum(array_column($enpData,'dme_new'));
            $other_new = array_sum(array_column($enpData,'other_new'));
            $pcv_new = array_sum(array_column($enpData,'pcv_new'));
            $wamd_new = array_sum(array_column($enpData,'wamd_new'));
            $enp = $dme_new + $other_new + $pcv_new + $wamd_new;

            $rate = ($esp + $enp ) == 0 ? 0 : $esp/($esp + $enp);
            $rate = round($rate, 4);
            $result['re_treatment_rate' . $x] = $this->formatDecimal($rate, 2) ;
        }

        return $this->success($result);

    }

    /**
     * 新增数据data
     * @param Request $request
     * @return array
     */
    public function create(Request $request){
        $params = $request->all();
        $result = Data::query()->insert($params);
        return $this->success($result);
    }


    /**
     * @param Request $request
     * @return array
     * @throws AppException
     */
    public function getInfo(Request $request)
    {
        $params = $request->all();
        if (!isset($params['member_id'])){
            throw new AppException('find_member_is_fail');
        }
        $memberData = Data::query()->where('member_id', $params['member_id'])->where('created_at', $params['created_at'])->first();
        if (!$memberData){
            //初始化一个数据
            $memberData['data_id'] = 0;
            $memberData['member_id'] = 0;
            $memberData['name'] = '';
            $memberData['province_info'] = '';
            $memberData['team_info'] = '';
            $memberData['rm_info'] = '';
            $memberData['dm_info'] = '';
            $memberData['dme_big'] = 0;
            $memberData['dme_new'] = 0;
            $memberData['dme_old'] = 0;
            $memberData['wamd_big'] = 0;
            $memberData['wamd_new'] = 0;
            $memberData['wamd_old'] = 0;
            $memberData['pcv_big'] = 0;
            $memberData['pcv_new'] = 0;
            $memberData['pcv_old'] = 0;
            $memberData['other_big'] = 0;
            $memberData['other_new'] = 0;
            $memberData['other_old'] = 0;
            $memberData['created_at'] = 0;
        }

        return $this->success($memberData, '获取成功');
    }

    /**
     * 处理小数点
     * @param $data
     * @param $number
     * @return false|string
     */
    function formatDecimal($data, $number)
    {
        $data = $data * 100;
        $pos = stripos((string)$data, '.');
        return substr((string)$data, 0, $pos + $number + 1);
    }

    /**
     * 获取微信js-sdk
     * @param Request $request
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getAccessToken(Request $request)
    {
        $url = $request->input('url');

        try {
            $endpoint = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxdce0bbe323228ace&secret=87d66a68ffe97006d20df338a3d91505";
//            $client = new \GuzzleHttp\Client();
//            $response = $client->request('get', $endpoint, [
//                'json' => [],
//                'headers' => []
//            ]);
//
//            $response = $response->getBody()->getContents();
//            $response = json_decode($response, true);
            $response = $this->geturl($endpoint);

            $accessToken = $response['access_token'];


            $tiket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$accessToken&type=jsapi";
//            $client = new \GuzzleHttp\Client();
//            $response = $client->request('get', $tiket, [
//                'json' => [],
//                'headers' => []
//            ]);
//            $response = $response->getBody()->getContents();
//            $response = json_decode($response, true);
            $response = $this->geturl($tiket);
            //生成签名
            $signTure = "jsapi_ticket=" .$response['ticket'] ."&noncestr=Wm3WZYTPz0wzccnW&timestamp=".time(). "&url=" . $url;

            $result['appId'] = 'wxdce0bbe323228ace';
            $result['timestamp'] = time();
            $result['noncestr'] = "Wm3WZYTPz0wzccnW";
            $result['signature'] = sha1($signTure);
            $result['ticket'] = $response['ticket'];

            return $this->success($result);
        } catch (\Exception $e) {
            $response = $e->getResponse()->getBody()->getContents();
        }
    }

    function geturl($url){
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }


    /**
     * 年月份处理
     * @param string $y
     * @param string $m
     * @return array
     */
    function getFirstAndLast( $y="",$m="" ){
        if($y=="") $y=date("Y");
        if($m=="") $m=date("m");
        $m=sprintf("%02d",intval($m));
        $y=str_pad(intval($y),4,"0",STR_PAD_RIGHT);
        $m>12 || $m<1 ? $m=1 :$m = $m;
        $firstDay=strtotime($y.$m."01000000");
        $firstDayStr=date("Y-m-01",$firstDay);
        $lastDay = strtotime(date('Y-m-d 23:59:59', strtotime("$firstDayStr +1 month -1 day")));
        return array("firstDay" => $firstDay,"lastDay" => $lastDay);
    }

    function getTheMonth($date)
    {
        $firstDay = date('Y-m-01', strtotime($date));
        $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
        return array($firstDay,$lastDay);
    }
}